from sqlalchemy.orm import Session
from fastapi import HTTPException, status

from app.repository import user_repo
from app.schemas.user import UserCreate
from app.core import security
from app.models.user import User


def register_new_user(db: Session, user_in: UserCreate) -> User:
    """
    处理新用户注册的业务逻辑。
    """
    # 1. 检查邮箱是否已被注册
    db_user = user_repo.get_user_by_email(db, email=user_in.email)
    if db_user:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Email already registered",
        )

    # 2. 对密码进行哈希
    hashed_password = security.get_password_hash(user_in.password)

    # 3. 创建用户
    user = user_repo.create_user(db=db, user=user_in, hashed_password=hashed_password)
    return user


def authenticate_user(db: Session, email: str, password: str) -> User | None:
    """
    处理用户认证的业务逻辑。
    """
    # 1. 查找用户
    user = user_repo.get_user_by_email(db, email=email)
    if not user:
        return None

    # 2. 验证密码
    if not security.verify_password(password, user.hashed_password):
        return None

    return user